#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Reason-GPL: import-scapy
import argparse
import os
import sys
from scapy.all import sniff

def pick_iface():
    ifaces = [i for i in os.listdir("/sys/class/net/") if "eth" in i]
    # 优先 *-eth0
    for i in ifaces:
        if i.endswith("-eth0"):
            return i
    return ifaces[0] if ifaces else None

def handle_pkt(pkt, quiet=False):
    if not quiet:
        print("got a packet")
        pkt.show()
        sys.stdout.flush()

def main():
    ap = argparse.ArgumentParser(description="ECMP/IPv4 作业用收包脚本（保持原文件名）")
    ap.add_argument("--iface", help="监听接口（默认自动选择 *-eth0）")
    ap.add_argument("--filter", default="tcp and dst port 1234", help='BPF 过滤表达式，默认 "tcp and dst port 1234"')
    ap.add_argument("--count", type=int, default=0, help="抓取报文个数；0=无限")
    ap.add_argument("--quiet", action="store_true", help="安静模式，不打印 show() 细节")
    args = ap.parse_args()

    iface = args.iface or pick_iface()
    if not iface:
        print("Cannot find interface")
        sys.exit(1)

    print(f"sniffing on {iface} with filter: {args.filter}")
    sys.stdout.flush()

    sniff(filter=args.filter, iface=iface, prn=lambda x: handle_pkt(x, args.quiet),
          store=0, count=args.count)

if __name__ == "__main__":
    main()
